package com.example.j202411.repository;

// ConstellationRepository.java
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.j202411.Model.ConstellationResponse;
import com.example.j202411.service.ConstellationService;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ConstellationRepository {
    private static final String BASE_URL = "https://api.lolimi.cn/";
    private ConstellationService constellationService;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    public ConstellationRepository() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        constellationService = retrofit.create(ConstellationService.class);
    }

    public LiveData<ConstellationResponse> getConstellationInfo(String constellation) {
        MutableLiveData<ConstellationResponse> data = new MutableLiveData<>();
        executorService.execute(() -> {
            constellationService.getConstellationInfo(constellation, "json").enqueue(new Callback<ConstellationResponse>() {
                @Override
                public void onResponse(@NonNull Call<ConstellationResponse> call, @NonNull Response<ConstellationResponse> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        data.postValue(response.body());
                    } else {
                        Log.e("ConstellationRepository", "Error getting data from API: " + response.code() + " " + response.message());
                        try {
                            Log.d("ConstellationRepository", "Response body: " + response.errorBody().string());
                        } catch (Exception e) {
                            Log.e("ConstellationRepository", "Error reading response body: " + e.getMessage());
                        }
                    }
                }

                @Override
                public void onFailure(@NonNull Call<ConstellationResponse> call, @NonNull Throwable t) {
                    Log.e("ConstellationRepository", "Error fetching data from API", t);
                }
            });
        });

        return data;
    }
}